# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
# esp.osdebug(None)
#import webrepl
# webrepl.start()
import utime
from machine import Pin
import network
from simple import MQTTClient
import deohttp
import helper
import utime
######
WIFI_SID = ""
WIFI_PW = ""

SOCKET_TIMEOUT = 30

MQ_SERVER_IP = "a1V4OoQSZWF.iot-as-mqtt.cn-shanghai.aliyuncs.com"
MQ_SERVER_PORT = "1883"

MQ_SERVER_USER = "LedCtrl&"
msg=""
MQ_SERVER_PW = ""

CLIENT_ID = ""

SCB_TOPIC = "/a1V4OoQSZWF/LedCtrl/user/led"
PUB_TOPIC = "/a1V4OoQSZWF/LedCtrl/user/led"
######


def on_msg(topic, msg):
    print("topic[%s]msg[%s]" % (topic, msg))


###
try:
    wlan = None
    qc = None
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    count = 0
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(WIFI_SID, WIFI_PW)
        while (not wlan.isconnected()) and count < 10:
            utime.sleep(1)
            count = count+1
        print('network config:', wlan.ifconfig())
    ######
    qc = MQTTClient(CLIENT_ID, MQ_SERVER_IP, MQ_SERVER_PORT,
                    MQ_SERVER_USER, MQ_SERVER_PW)
    qc.timeout = SOCKET_TIMEOUT
    print('mq init.')
    qc.set_callback(on_msg)
    print('mq callback.')
    qc.connect()
    print('mq connect.')
    qc.subscribe(SCB_TOPIC)
    print('mq s.')
    qc.publish(PUB_TOPIC, "hello! from espressif.", retain=True)
    print('mq p.')
    count = 0
    while count < 1:
        qc.wait_msg()
        count = count+1
finally:
    if qc is not None:
        qc.disconnect()
    if wlan is not None:
        wlan.disconnect()
        wlan.active(False)
######
